<template>
  <a-layout>
    <a-layout>
      <a-layout style="padding: 0 24px">
        <a-layout-content :style="{ background: '#fff', padding: '24px', margin: 0, minHeight: '280px' }">
          <a-row>
            <a-col :span="12">
              <a-row>
                <a-col :span="8">
                  <a-input v-model:value="searchObj.name" size="middle" placeholder="查询名称"/>
                </a-col>
                <a-col :span="8">
                  <a-button size="middle" type="primary" @click="handlerSearch">查询</a-button>
                  <a-button size="middle" type="primary" @click="handlerAdd">新增</a-button>
                </a-col>
              </a-row>
              <a-table
                  :columns="columns"
                  :data-source="tableData"
                  :rowKey="record => record.id"
                  :pagination="false">
                <template v-slot:action="{text,record}">
                  <a-button size="middle" type="primary" @click="handlerEdit(record)">编辑</a-button>
                  <a-button size="middle" :danger="true" @click="handlerRemove(record)">删除</a-button>
                </template>
              </a-table>
            </a-col>
            <a-col :span="12">
              <a-button size="middle" type="primary" @click="handlerModalOk">保存</a-button>
              <a-form :model="formDoc" :label-col="formLabelCol" :wrapper-col="formWrapperCol" layout="vertical">
                <a-form-item label="父级" v-if="formDoc.parent != 0">
                  <a-tree-select
                      v-model:value="formDoc.parent"
                      show-search
                      style="width: 100%"
                      :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                      placeholder="Please select"
                      allow-clear
                      tree-default-expand-all
                      :replaceFields="fieldNames"
                      :tree-data="treeData">
                  </a-tree-select>
                </a-form-item>
                <a-form-item label="名称">
                  <a-input v-model:value="formDoc.name"/>
                </a-form-item>
                <a-form-item label="排序">
                  <a-input v-model:value="formDoc.sort"/>
                </a-form-item>
                <a-form-item label="内容">
                  <div id="content"></div>
                </a-form-item>
              </a-form>
            </a-col>
          </a-row>
        </a-layout-content>

      </a-layout>
    </a-layout>
  </a-layout>

</template>

<script>
import {onMounted, ref} from "vue";
import * as doc from "@/api/wiki/doc"
import {message, Modal} from "ant-design-vue";
import E from 'wangeditor'

const {useRoute} = require("vue-router");

export default {
  name: "AdminDoc",
  setup() {
    const tableData = ref([])
    const treeData = ref([])
    const columns = ref([
      {
        title: '名称',
        dataIndex: 'name',
        key: 'name'
      },
      {
        title: '排序',
        dataIndex: 'sort',
        key: 'sort'
      }, {
        title: '操作',
        dataIndex: 'action',
        slots: {customRender: 'action'}
      }])
    const loading = ref(true)
    const fieldNames = ref({children: 'children', label: 'name', key: 'id', value: 'id'})
    //对话框是否可见
    //确定按钮 loading
    const formDoc = ref({})
    const formLabelCol = ref({span: 4})
    const formWrapperCol = ref({span: 14})
    const searchObj = ref({})
    const docs = ref([])
    const route = useRoute()
    let editor

    console.log('路由', route)
    console.log('route.path', route.path)
    console.log('route.query', route.query)
    console.log('route.params', route.params)
    console.log('route.fullPath', route.fullPath)
    console.log('route.name', route.name)
    console.log('route.meta', route.meta)

    const handlerQuery = (params) => {
      doc.docs(params).then(res => {
        if (res.success) {
          tableData.value = res.data
          treeData.value = res.data
          loading.value = false
        } else {
          message.error(res.msg);
        }
      })
    }

    const handlerSearch = () => {
      searchObj.value.current = 1
      searchObj.value.size = 2
      searchObj.value.ebookId = route.query.ebookId
      handlerQuery(searchObj.value)
    }

    const handlerEdit = (record) => {
      doc.doc(record.id).then(res => {
        if (res.status === 200) {
          let data = res.data
          formDoc.value = JSON.parse(JSON.stringify(data))
          editor.txt.html(data.content)
        } else {
          message.error(res.msg)
        }
      })
    }

    const handlerAdd = () => {
      formDoc.value = {}
      editor.txt.html('')
    }

    const getIdArr = (children, idArr) => {
      if (children)
        children.forEach((ele) => {
          idArr.push(ele.id);
          if (ele.children) {
            getIdArr(ele.children, idArr);
          }
        });
    }

    const handlerRemove = (record) => {
      Modal.confirm({
        title: '删除',
        content: '确定要删除这些数据吗?',
        okText: '确定',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          let idArr = []
          getIdArr([record], idArr)
          if (!idArr) {
            message.warn('选中文档节点不可为空')
            return
          }
          doc.remove(idArr.join()).then(res => {
            if (res.status === 200) {
              message.success(res.msg);
              handlerQuery({ebookId: route.query.ebookId})
            } else {
              message.error(res.msg);
            }
          })
        },
        onCancel() {
        },

      });
    }

    const handlerModalOk = () => {
      if (!route.query.ebookId) {
        return message.error('未选择文档对应的电子书')
      }
      formDoc.value.content = editor.txt.html()
      formDoc.value.ebookId = route.query.ebookId
      if (formDoc.value.id) {
        doc.update(formDoc.value).then(res => {
          if (res.status === 200) {
            message.success(res.msg);
            handlerQuery({ebookId: route.query.ebookId})
          } else {
            message.error(res.msg);
          }
        })
      } else {
        doc.save(formDoc.value).then(res => {
          if (res.success) {
            message.success(res.msg);
            handlerQuery({ebookId: route.query.ebookId})
          } else {
            message.error(res.msg);
          }
        })
      }

    }

    const initWangEditor = () => {
      editor = new E("#content")
      editor.create()
    }

    onMounted(() => {
      if (!route.query.ebookId) {
        return message.error('未选择文档对应的电子书')
      }
      initWangEditor()
      handlerQuery({ebookId: route.query.ebookId})
    })
    return {
      columns,
      tableData,
      treeData,
      loading,
      searchObj,
      docs,
      formDoc,
      formLabelCol,
      formWrapperCol,
      // tree name
      fieldNames,

      handlerSearch,
      handlerRemove,
      handlerAdd,
      handlerEdit,
      handlerModalOk

    }
  }
}
</script>

<style scoped>

</style>
